<template>
  <div>
    <!-- 新增角色按钮 -->
    <el-row style="height: 60px">
      <el-button
        icon="el-icon-plus"
        size="small"
        type="primary"
        @click="addRole"
      >新增角色</el-button>
    </el-row>
    <!-- 表格 -->
    <el-table border="" :data="roleList" stripe style="width: 100%">
      <el-table-column label="序号" width="120" type="index" align="center" />
      <el-table-column
        label="角色名称"
        width="240"
        prop="name"
        align="center"
      />
      <el-table-column label="描述" prop="description" align="center" />
      <el-table-column label="操作" align="center">
        <template v-slot="{ row }">
          <el-button size="small" type="success">分配权限</el-button>
          <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
          <el-button size="small" type="danger" @click="delRole(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-row type="flex" justify="end" align="middle" style="height: 60px">
      <!-- 分页组件 -->
      <el-pagination
        layout="prev, pager, next"
        :total="page.total"
        :current-page="page.page"
        :page-size="page.pagesize"
        @current-change="changePage"
      />
    </el-row>

    <!-- 弹出层 -->
    <AddRole ref="addRole" :show-dialog.sync="showDialog" :page="page" />
  </div>
</template>

<script>
import { getRoleList, getRoleDetail, delRole } from '@/api/setting'
// import { getDepartments } from '@/api/departments'
import AddRole from './add-role'
export default {
  name: 'Role',

  components: {
    AddRole
  },

  data() {
    return {
      roleList: [], // 承接数组
      page: {
        // 放置页码及相关数据
        page: 1,
        pagesize: 10,
        total: 0 // 记录总数
      },
      showDialog: false

    }
  },

  created() {
    this.getRoleList()
  },

  methods: {
    // 获取角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.page)
      this.roleList = rows
      this.page.total = total
    },

    // 页码变化
    changePage(newPaage) {
      this.page.page = newPaage
      this.getRoleList()
    },

    // 添加角色
    addRole() {
      this.showDialog = true
    },

    // 编辑角色
    async editRole(id) {
      // const { companyId } = await getDepartments()
      // this.$refs.addRole.roleForm = { companyId: companyId, ...await getRoleDetail(id) }
      this.$refs.addRole.roleForm = { companyId: this.$store.getters.companyId, ...await getRoleDetail(id) }
      this.showDialog = true
    },

    // 删除角色
    async delRole(id) {
      try {
        await this.$confirm('确定要删除该角色吗？')
        await delRole(id)
        this.getRoleList()
        this.$message.success('删除角色成功！')

        if (this.roleList.length === 1) {
          this.page.page--
          this.getRoleList()
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style>
</style>
